﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Helper
{
    public class UrlFileHelper
    {
        /// <summary>
        /// 获取指定文件大小
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static long GetUrlFileSize(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "HEAD"; // 使用 HEAD 方法获取响应头

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    string contentLength = response.Headers.Get("Content-Length");
                    if (!string.IsNullOrEmpty(contentLength))
                    {
                        long fileSize = long.Parse(contentLength);
                        return fileSize;
                    }
                }
            }
            catch (Exception ex)
            {
                //LogTool.Instance.AddLogAndDisp($"获取文件大小失败：{ex.Message}", EnumLogLevel.Error);
            }
            return -1; // 获取文件大小失败
        }
        /// <summary>
        /// 获取指定文件夹下的文件列表
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static List<string> GetUrlFileList(string url)
        {
            List<string> fileList = new List<string>();

            try
            {
                using (WebClient client = new WebClient())
                {
                    string htmlContent = client.DownloadString(url);
                    if (htmlContent.Contains("<a href="))
                    {
                        string[] lines = htmlContent.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string line in lines)
                        {
                            if (line.Contains("<a href="))
                            {
                                string[] parts = line.Split(new string[] { "<a href=\"" }, StringSplitOptions.RemoveEmptyEntries);
                                if (parts.Length > 1)
                                {
                                    string fileName = parts[1].Split('"')[0];
                                    fileList.Add(fileName);
                                }
                            }
                        }
                    }
                    else
                    {
                        HtmlDocument doc = new HtmlDocument();
                        doc.LoadHtml(htmlContent);
                        // 选择所有的<a>标签
                        var linkNodes = doc.DocumentNode.SelectNodes("//pre/a");

                        // 输出链接文本
                        if (linkNodes != null)
                        {
                            foreach (var link in linkNodes)
                            {
                                fileList.Add(link.InnerText);
                            }
                        }
                    }
                }
                if (fileList.Count > 0)
                {
                    fileList.RemoveAt(0);
                }
            }
            catch (Exception ex)
            {
                //LogTool.Instance.AddLogAndDisp($"获取文件列表失败：{ex.Message}", EnumLogLevel.Error);
            }
            return fileList;
        }
        /// <summary>
        /// 异步下载文件
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="localPath">本地保存路径</param>
        /// <param name="downloadProgressChangedHandler">下载进度展示句柄</param>
        /// <param name="downloadFileCompletedHandler">下载成功句柄</param>
        public static void DownloadFileAsync(string url, string localPath, DownloadProgressChangedEventHandler downloadProgressChangedHandler, AsyncCompletedEventHandler downloadFileCompletedHandler)
        {
            if (string.IsNullOrEmpty(url))
            {
                //LogTool.Instance.AddLogAndDisp("请指定要下载的文件地址", EnumLogLevel.Error);
                return;
            }
            string dir = Directory.GetParent(localPath).FullName;
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            WebClient client = new WebClient();
            client.DownloadProgressChanged += downloadProgressChangedHandler;
            client.DownloadFileCompleted += downloadFileCompletedHandler;
            
            try
            {
                client.DownloadFileAsync(new Uri(url), localPath);
            }
            catch (Exception ex)
            {
                //LogTool.Instance.AddLogAndDisp($"下载文件失败：{ex.Message}", EnumLogLevel.Error);
            }
        }
    }
}
